//
//  GGPermissionsManage.m
//  Brezze
//
//  Created by IOS on 2021/7/6.
//  Copyright © 2021 麦鱼科技. All rights reserved.
//

#import "GGPermissionsManage.h"
#import <AVFoundation/AVFoundation.h>
#import <Photos/Photos.h>

@implementation GGPermissionsManage

+ (void)checkLocationsPer:(CheckStatus)succ faile:(CheckStatus)faile {
    
    CLAuthorizationStatus status = [CLLocationManager authorizationStatus];
    [self checkLocationsPer:succ faile:faile byStatus:status];
}

+ (void)checkLocationsPer:(CheckStatus)succ faile:(CheckStatus)faile byStatus:(CLAuthorizationStatus)status {
    
    if (status == kCLAuthorizationStatusAuthorizedWhenInUse || status == kCLAuthorizationStatusAuthorizedAlways) {
        
        succ();
    }else if (status == kCLAuthorizationStatusDenied) {
        faile();
        // 显示提示信息，允许用户选择取消或前往系统设置（用户主动点击才跳转，符合 Apple 审核要求）
        [self alerCInit:Localized(@"Permission_Location_title") subTitle:Localized(@"Permission_Location_Message") cancelBlock:^{
            
        } sureBlock:^{
            // 用户主动点击"前往系统设置"按钮时才跳转
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString] options:@{} completionHandler:nil];
        }];
    } else if (status == kCLAuthorizationStatusNotDetermined) {
        // 权限未确定时，不显示提示，直接调用 faile，让调用方处理权限请求
        faile();
    }
}


+ (void)checkCameraPer:(CheckStatus)succ faile:(CheckStatus)faile {
    
    AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
    if(authStatus == AVAuthorizationStatusRestricted || authStatus == AVAuthorizationStatusDenied){
        faile();
        // 显示提示信息，允许用户选择取消或前往系统设置（用户主动点击才跳转，符合 Apple 审核要求）
        [self alerCInit:Localized(@"Permission_Camera_title") subTitle:Localized(@"Permission_Camera_Message") cancelBlock:^{
            
        } sureBlock:^{
            // 用户主动点击"前往系统设置"按钮时才跳转
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString] options:@{} completionHandler:nil];
        }];
        return;
    }else if(authStatus == AVAuthorizationStatusNotDetermined) {
        // 如果权限未确定，先请求权限
        [AVCaptureDevice requestAccessForMediaType:AVMediaTypeVideo completionHandler:^(BOOL granted) {
            dispatch_async(dispatch_get_main_queue(), ^{
                if (granted) {
                    succ();
                } else {
                    faile();
                    // 用户拒绝后，显示提示，允许用户选择前往设置
                    [self alerCInit:Localized(@"Permission_Camera_title") subTitle:Localized(@"Permission_Camera_Message") cancelBlock:^{
                        
                    } sureBlock:^{
                        // 用户主动点击"前往系统设置"按钮时才跳转
                        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString] options:@{} completionHandler:nil];
                    }];
                }
            });
        }];
        return;
    }else {
        succ();
    }
}

+ (void)checkPhotosOpenPer:(CheckStatus)succ faile:(CheckStatus)faile {
    
    PHAuthorizationStatus status = [PHPhotoLibrary authorizationStatus];
    if (status == PHAuthorizationStatusRestricted || status == PHAuthorizationStatusDenied){
        faile();
        // 显示提示信息，允许用户选择取消或前往系统设置（用户主动点击才跳转，符合 Apple 审核要求）
        [self alerCInit:Localized(@"Permission_Photos_title") subTitle:Localized(@"Permission_Photos_Message") cancelBlock:^{
            
        } sureBlock:^{
            // 用户主动点击"前往系统设置"按钮时才跳转
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString] options:@{} completionHandler:nil];
        }];
        return;
    }else {
        succ();
    }
}

+ (void)checkPhotosNotDeterminedr:(CheckStatus)succ faile:(CheckStatus)faile {
    
    PHAuthorizationStatus status = [PHPhotoLibrary authorizationStatus];
    if (status == PHAuthorizationStatusNotDetermined ){
        faile();
        // 显示提示信息，允许用户选择取消或前往系统设置（用户主动点击才跳转，符合 Apple 审核要求）
        [self alerCInit:Localized(@"Permission_Photos_title") subTitle:Localized(@"Permission_Photos_Message") cancelBlock:^{
            
        } sureBlock:^{
            // 用户主动点击"前往系统设置"按钮时才跳转
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString] options:@{} completionHandler:nil];
        }];
        return;
    }else {
        succ();
    }
}

+ (void)alerCInit:(NSString *)title subTitle:(NSString *)subTitle cancelBlock:(nullable CheckStatus)cancelBlock sureBlock:(CheckStatus)sureBlock {
    
    [self alerCInit:title subTitle:subTitle cancelTitle:Localized(@"Permission_Back") sureTitle:Localized(@"Permission_ToSeting") cancelBlock:cancelBlock sureBlock:sureBlock];
}

+ (void)alerCInit:(NSString *)title subTitle:(NSString *)subTitle cancelTitle:(nullable NSString *)cancelTitle sureTitle:(NSString *)sureTitle cancelBlock:(nullable CheckStatus)cancelBlock sureBlock:(CheckStatus)sureBlock {
    UIAlertController *alC = [UIAlertController alertControllerWithTitle:title message:subTitle preferredStyle:UIAlertControllerStyleAlert];
    
    UIAlertAction *cancelAction;
    UIAlertAction *sureAction;
    
    // 如果 sureBlock 为 nil，说明不需要跳转按钮（符合 Apple 审核要求）
    if (sureBlock == nil) {
        // 只添加取消/确定按钮，不提供跳转功能
        NSString *confirmTitle = cancelTitle ?: Localized(@"Permission_Back") ?: @"确定";
        cancelAction = [UIAlertAction actionWithTitle:confirmTitle style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
            if (cancelBlock) {
                cancelBlock();
            }
        }];
        // 返回按钮使用蓝色，避免歧义
        [cancelAction setValue:kColorMain forKey:@"titleTextColor"];
        [alC addAction:cancelAction];
    } else if (cancelTitle == nil || [cancelTitle isEqualToString:@""]) {
        /*
         * 创建确认Btn
         */
        sureAction = [UIAlertAction actionWithTitle:sureTitle style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            if (sureBlock != nil) {
                sureBlock();
            }
        }];
        [sureAction setValue:kColorMain forKey:@"titleTextColor"];
        [alC addAction:sureAction];
    }else{
        /*
         * 创建取消、确认Btn
         */
        cancelAction = [UIAlertAction actionWithTitle:cancelTitle style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
            
            if (cancelBlock) {
                cancelBlock();
            }
        }];
        sureAction = [UIAlertAction actionWithTitle:sureTitle style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            if (sureBlock != nil) {
                sureBlock();
            }
        }];
        // 返回按钮使用蓝色，避免歧义
        [cancelAction setValue:kColorMain forKey:@"titleTextColor"];
        [sureAction setValue:kColorMain forKey:@"titleTextColor"];
        [alC addAction:sureAction];
        [alC addAction:cancelAction];
    }
    
    UIViewController *showCtl = [UIApplication sharedApplication].keyWindow.rootViewController;
    [showCtl presentViewController:alC animated:YES completion:nil];
    
}



@end
